import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import java.util.concurrent.*;

// 使用Callable接口实现多线程
public class Thread05 implements Callable<Boolean> {
    private String url;
    private String name;
    public Thread05(String url, String name) {
        this.url=url;
        this.name=name;
    }
    @Override
    public Boolean call()  {   // throws Exception
        webDownloader webDownloader=new webDownloader();
        webDownloader.downloader(url,name);
        System.out.println(name+"的图片下载了。");
        return true;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread05 t1=new Thread05("https://tse3-mm.cn.bing.net/th/id/OIP-C.8l62NACpEMRVFlJaZNSXlgHaEK?w=332&h=187&c=7&r=0&o=5&pid=1.7","img1");
        Thread05 t2=new Thread05("https://tse1-mm.cn.bing.net/th/id/OIP-C.U_uj1lJJzLqyAf1WljIAVAHaE2?w=284&h=187&c=7&r=0&o=5&pid=1.7","img2");
        Thread05 t3=new Thread05("https://tse2-mm.cn.bing.net/th/id/OIP-C.3P-cWsf0agdOKV3_lAIvjQHaEo?w=290&h=181&c=7&r=0&o=5&pid=1.7","img3");
        // 创建执行服务
        ExecutorService ser= Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> r1=ser.submit(t1);
        Future<Boolean> r2=ser.submit(t2);
        Future<Boolean> r3=ser.submit(t3);
        // 获取结果
        boolean res1=r1.get();
        boolean res2=r2.get();
        boolean res3=r3.get();
        // 关闭服务
        ser.shutdownNow();
    }
}

class webDownloader {
    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题。");
        }
    }
}


